package com.xiaoke.validator;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoke.annotation.CategoryExist;
import com.xiaoke.domain.entity.Category;
import com.xiaoke.service.CategoryService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import static com.xiaoke.constants.SystemConstants.STATUS_NORMAL;

@Component
public class CategoryExistValidator implements ConstraintValidator<CategoryExist, Integer> {

    @Resource
    CategoryService categoryService;

    /**
     * 判断分类是否存在
     * @param id 分类ID
     */
    @Override
    public boolean isValid(Integer id, ConstraintValidatorContext constraintValidatorContext) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getStatus,STATUS_NORMAL)
                    .eq(Category::getId,id);
        int count = categoryService.count(queryWrapper);
        return count > 0;
    }
}
